package jmine.tec.web.wicket.component.autocomplete;

import java.io.Serializable;
import java.util.Collections;
import java.util.Iterator;

import jmine.tec.web.wicket.converter.NaturalKeyConverter;
import jmine.tec.web.wicket.validator.NaturalKeyIValidator;

import org.apache.commons.lang.StringUtils;
import org.apache.wicket.model.IModel;
import org.apache.wicket.util.convert.IConverter;

import bancosys.tec.persist.Persistable;

/**
 * @author seiti Nov 23, 2011
 * @param <P> persistable
 */
public class NaturalKeyAutocomplete<P extends Persistable & Serializable> extends CustomAutocompleteTextField<P> {

    private Class<P> persistable;

    /**
     * Ctor
     * 
     * @param persistableClass {@link Class}
     * @param id the wicket component id
     */
    public NaturalKeyAutocomplete(Class<P> persistableClass, String id) {
        this(persistableClass, id, true);
        setType(persistableClass);
    }

    /**
     * Ctor
     * 
     * @param persistableClass {@link Class}
     * @param id the wicket component id
     * @param validate se deve validar o input
     */
    public NaturalKeyAutocomplete(Class<P> persistableClass, String id, boolean validate) {
        super(id, (IModel<P>) null, NaturalKeyAutoCompleteTextRenderer.<P> instance());
        if (validate) {
            this.add(new NaturalKeyIValidator<P>(persistableClass));
        }
        setType(persistableClass);
        this.persistable = persistableClass;
    }

    /**
     * {@inheritDoc}
     */
    @SuppressWarnings("unchecked")
    @Override
    protected Iterator<P> getChoices(String input) {
        if (StringUtils.isEmpty(input)) {
            return Collections.<P> emptyList().iterator();
        }
        return (Iterator<P>) new NaturalKeyChoicesLoader<P>(this.persistable).getChoices(input);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public IConverter getConverter(Class<?> type) {
        return new NaturalKeyConverter(this.persistable);
    }
}
